<template>
  <div class="Aavatar">
    <div class="Aavatar_btn" @click="imagecropperShow=true">
      <img v-show="value" :src="value" class="Aavatar_bg">
    </div>
    <p class="Aavatar_title" :class="{'Aavatar_error': isError}">{{title}}</p>
    <image-cropper
      field="uploadFile"
      :maxSize='2000'
      :width="100" :height="100" @close='imagecropperShow = false' @crop-upload-success="cropSuccess"
      :key="imagecropperKey" :noRotate='false'
      v-show="imagecropperShow"></image-cropper>
  </div>
</template>

<script>
import ImageCropper from '~/components/ImageCropper'
import {uploadImage} from '~/api/'
import AvatarImg from '~/static/images/avatar.png'
  export default {
    components: {
      ImageCropper
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      isError: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '点击上传或修改头像'
      }
    },
    data() {
      return {
        AvatarImg,
        imagecropperShow: false,
        imagecropperKey: 0,
      }
    },
    methods: {
      async cropSuccess(file) {
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
        console.log(file)
        const res = await uploadImage(this, file)
        if (res.code == '0') {
          this.$message.success('图片上传成功')
          this.$emit('input', res.data.url)
        } else {
          this.$message.error(res.message)
        }
      }
    },
  }
</script>

<style lang="scss" scoped>
.Aavatar {
  &_btn {
    position: relative;
    width: 150px;
    height: 110px;
    line-height: 110px;
    background-color: #fff;
    border:  1px dashed #c0ccda;
    transition: border-color 200ms;
    text-align: center;
    &:hover {
      cursor: pointer;
      border-color: #409EFF;
    }
    &:before {
      content: "";
      width: 150px;
      height: 110px;
      position: absolute;
      top: 0;
      left: 0;
      background: url('~/static/images/login/button_addto_default.png') center center no-repeat;
      background-size: 25px 25px;
    }
  }
  &_bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    vertical-align: middle;
  }
  &_title {
    text-align: center;
    font-size: 12px;
    color: #666;
    margin-top: 10px;
  }
  &_error {
    color: #f00;
  }
}
</style>
